﻿using WHLRDF.Code.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using WHLRDF.ORM;

namespace WHLRDF.Code.BLL
{
    public class CodeDomain: SerivceBase,IDisposable
    {
        /// <summary>
        /// 命名空间
        /// </summary>
        public string Namespace { get; set; }
        /// <summary>
        /// 表名
        /// </summary>
        public string TableName { get; set; }
        /// <summary>
        /// 是否是表
        /// </summary>
        public bool IsTable { get; set; }
        /// <summary>
        /// 数据源类型
        /// </summary>
        public int ProviderType { get; set; }

        private string _className;
        /// <summary>
        /// 类名
        /// </summary>
        public string ClassName
        {
            get
            {
                if (string.IsNullOrWhiteSpace(_className))
                {
                    _className= TableName;
                    if (_className.IndexOf("_") != -1)
                    {
                        _className= _className.Substring(_className.IndexOf("_") + 1);
                    }
                }
                return _className;

            }
            set
            {
                _className = value;
            }
        }

        private DbColumnEntity primaryEntity;
        /// <summary>
        /// 主键字段对象
        /// </summary>
        public DbColumnEntity PrimaryEntity
        {
            get {
               
                if (primaryEntity == null)
                {
                    primaryEntity = columnEntities.Where(x=>x.IsPrimary).FirstOrDefault();
                }
                return primaryEntity;
            }
        }

        /// <summary>
        /// 表
        /// </summary>
        public DbTableEntity tableEntity { get; set; }

        /// <summary>
        /// 属性
        /// </summary>
        public List<DbColumnEntity> columnEntities { get; set; }

        /// <summary>
        /// 系统字段
        /// </summary>
        public const string SystemField = "createby;createdate;lastmodifyuserid;lastmodifydate,isdeleted";

        private List<SysFieldTypeEntity> codeDbTypeEntities { get; set; }

        private List<DbFieldRelationTypeEntity> dbTypeEntities { get; set; }

        public CodeDomain()
        {

        }
        /// <summary>
        /// 通过表id构造函数
        /// </summary>
        /// <param name="tableid"></param>
        public CodeDomain(string tableid)
        {
            var table = new DbTableEntity() ;
            int providerType = 0;
            codeDbTypeEntities = this.CacheService.GetOrCreate<List<SysFieldTypeEntity>>("CodeDomain_CodeDbType_All",()=> {
                return new SysFieldTypeService().GetAll();
            });
            columnEntities = new DbCodeService().GetColumns(tableid, ref table, ref providerType, false);
            
            tableEntity = table;
            if (tableEntity != null)
            {
                dbTypeEntities = this.CacheService.GetOrCreate<List<DbFieldRelationTypeEntity>>("CodeDomain_CodeDbType_All_"+ tableEntity.ProviderType.ToString(), () => {
                    return new DbFieldRelationTypeService().GetAll((ProviderType)tableEntity.ProviderType);
                });
                this.TableName = tableEntity.DbTableName;
                this.Namespace = !string.IsNullOrWhiteSpace(tableEntity.DbNamespace)? tableEntity.DbNamespace:"NetCore";
                this.IsTable = tableEntity.IsTable;
                this.ProviderType = tableEntity.ProviderType;
            }
        }

        /// <summary>
        /// 通过表名 以及数据库名构造
        /// </summary>
        /// <param name="tablename"></param>
        /// <param name="dbserverName"></param>
        public CodeDomain(string tablename,string dbserverName)
        {
           
        }
        ~CodeDomain()
        {

        }
        public CodeDomain(DbTableEntity dbTable)
        {
            tableEntity = dbTable;
            if (tableEntity != null)
            {
                this.TableName = tableEntity.DbTableName;
                this.Namespace = !string.IsNullOrWhiteSpace(tableEntity.DbNamespace) ? tableEntity.DbNamespace : "WHLRDF";
                this.IsTable = tableEntity.IsTable;
                this.ProviderType = tableEntity.ProviderType;
            }
        }
        private Dictionary<string, SysFieldTypeEntity> lstDbType;

      
        public string GetDbType(string dbTypeName, int ProvderType, bool isDbNull, ref string VaildKey)
        {
            if (lstDbType == null)
            {
                lstDbType = new Dictionary<string, SysFieldTypeEntity>();
            }

            if (!lstDbType.ContainsKey(dbTypeName.ToLower())
                || lstDbType[dbTypeName.ToLower()] == null)
            {
               var dbType=  dbTypeEntities.Where(x => x.DbTypeName.Equals(dbTypeName)).FirstOrDefault();
                if (dbType != null)
                {
                    lstDbType[dbTypeName.ToLower()]= codeDbTypeEntities.Where(x => x.SysFieldTypeId == dbType.SysFieldTypeId).FirstOrDefault();
                }

            }
            if (lstDbType[dbTypeName.ToLower()] != null)
            {
                SysFieldTypeEntity entity = lstDbType[dbTypeName.ToLower()];
               
                if (entity != null)
                {
                    string strdbType = entity.DbTypeName;
                    if (isDbNull && entity.IsDbNull)
                    {
                        strdbType += "?";
                    }
                    VaildKey = entity.VaildKey;
                    return strdbType;
                }
            }
            return "string";

        }
        public string GetControlType(int controlType)
        {
         
            return ((ControlType)controlType).ToString();

        }
        /// <summary>
        /// 获取默认值的方法
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="providerType"></param>
        /// <returns></returns>
        public string GetDefault(DbColumnEntity entity, int providerType)
        {
            if (!string.IsNullOrEmpty(entity.DefaultValue))
            {
                string VaildKey = "";
                string dbType = GetDbType(entity.DbTypeName, providerType, entity.AllowDBNull, ref VaildKey).ToLower();
                if (dbType.IndexOf("datetime") == -1)
                {
                    return entity.DefaultValue.Replace("(", "").Replace(")", "").Replace("''", "");
                }
            }
            return "";
        }
     


        public DbColumnEntity GetPrimaryKey(List<DbColumnEntity> dbColumns)
        {
            return dbColumns.Where(x => x.IsPrimary).FirstOrDefault();

        }

        public bool Contains(string field)
        {
           var FilterField= SystemField.Split(new char[] { ';',','});
            if (FilterField == null || FilterField.Length <= 0 || string.IsNullOrWhiteSpace(field))
            {
                return false;
            }
            return FilterField.Contains(field.ToLower());
        }

    }
}
